<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch, shallowRef, onBeforeUnmount, Ref } from 'vue'
import { FormInstance, Message } from '@arco-design/web-vue'
import { IconPlus } from '@arco-design/web-vue/es/icon'
import dayjs from 'dayjs'
import { addMilestoneUsingPost } from '@/api/milestoneController'
import { addIterationUsingPost } from '@/api/iterationController'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { IEditorConfig, IDomEditor } from '@wangeditor/editor'
import utc from 'dayjs/plugin/utc'
import { editorConfig, editorStyle } from '@/composables/useEditorConfig'
import { PRIORITY_CONFIG, getTaskPriorityColor, getPriorityLabel } from '@/constants/Priority'
import { addTaskUsingPost } from '@/api/taskController'
import {
  COMPLETE_STATUS_CONFIG,
  getCompleteStatus,
  getCompleteColor
} from '@/constants/CompleteStatus'
import { addRequirementUsingPost } from '@/api/requirementController'
import TaskView from '@/components/tasks/TaskView.vue'
import RequirementView from '@/components/requirements/RequirementView.vue'
import MileStoneView from '@/components/milestones/MileStoneView.vue'
import IterationView from '@/components/iterations/IterationView.vue'
// Props定义
const props = withDefaults(
  defineProps<{
    projectVo: API.ProjectVo
  }>(),
  {}
)

// Emits定义
const emit = defineEmits<{
  (e: 'reload', refresh?: boolean): void // type 是可选参数
}>()

// 分页显示控制
const displayCounts = reactive({
  projectTasks: 5,
  milestoneTasks: {} as Record<number, number>,
  iterationTasks: {} as Record<number, number>,
  requirementTasks: {} as Record<number, number>
})

// 弹窗控制
const milestoneModalVisible = ref(false)
const iterationModalVisible = ref(false)
const requirementModalVisible = ref(false)
const taskModalVisible = ref(false)

// 当前选中项
const currentMilestone = ref<API.MileStoneVo | null>(null)
const currentIteration = ref<API.IterationVo | null>(null)
const currentRequirement = ref<API.RequirementVo | null>(null)
const currentTask = ref<API.TaskVo | null>(null)

// 详情弹窗控制
const selectedMilestone = ref<API.MileStoneVo | null>(null)
const selectedIteration = ref<API.IterationVo | null>(null)
const selectedRequirement = ref<API.RequirementVo | null>(null)
const selectedTask = ref<API.TaskVo | null>(null)

// 编辑器相关的状态
const milestoneDescriptionEditor = shallowRef()
const milestoneRemarkEditor = shallowRef()
const iterationDescriptionEditor = shallowRef()
const iterationRemarkEditor = shallowRef()

// 添加需求和任务的编辑器实例
const requirementDescriptionEditor = shallowRef()
const requirementRemarkEditor = shallowRef()
const taskDescriptionEditor = shallowRef()
const taskRemarkEditor = shallowRef()

// 需求表单数据
const addRequirementRequest: Ref<API.AddRequirementRequest> = ref({
  title: '',
  description: '',
  remark: '',
  priority: 0,
  itrId: undefined as number | undefined,
  mileId: undefined as number | undefined,
  proId: props.projectVo?.id as number | undefined,
  startTime: props.projectVo?.startTime || '',
  endTime: props.projectVo?.endTime || ''
})
// 任务表单数据
const addTaskRequest: Ref<API.AddTaskRequest> = ref({
  proId: undefined as number | undefined,
  mileId: undefined as number | undefined,
  iterId: undefined as number | undefined,
  reqId: undefined as number | undefined,
  ownerId: undefined as number | undefined,
  startTime: '',
  endTime: '',
  title: '',
  description: '',
  remark: '',
  priority: 0 // 设置默认优先级为 P0
})
// 添加表单引用
const milestoneFormRef = ref()
const iterationFormRef = ref()

// 添加表单规则
const milestoneRules = {
  title: [
    { required: true, message: '请输入里程碑标题' },
    { maxLength: 50, message: '标题最多50个字符' }
  ],
  startTime: [{ required: true, message: '请选择开始时间' }],
  endTime: [{ required: true, message: '请选择结束时间' }]
}

const iterationRules = {
  title: [
    { required: true, message: '请输入迭代标题' },
    { maxLength: 50, message: '标题最多50个字符' }
  ],
  startTime: [{ required: true, message: '请选择开始时间' }],
  endTime: [{ required: true, message: '请选择结束时间' }]
}

const requirementRules = {
  title: [
    { required: true, message: '请输入需求标题' },
    { maxLength: 50, message: '标题最多50个字符' }
  ],
  priority: [{ required: true, message: '请选择优先级' }],
  startTime: [{ required: true, message: '请选择开始时间' }],
  endTime: [{ required: true, message: '请选择结束时间' }],
  ownerId: [{ required: true, message: '请选择负责人' }]
}

// 添加任务表单规则
const taskRules = {
  title: [
    { required: true, message: '请输入任务标题' },
    { maxLength: 50, message: '标题最多50个字符' }
  ],
  priority: [{ required: true, message: '请选择优先级' }],
  ownerId: [{ required: true, message: '请选择负责人' }],
  startTime: [{ required: true, message: '请选择开始时间' }],
  endTime: [{ required: true, message: '请选择结束时间' }]
}

// 通用的时间变更处理函数
const handleTimeChange = (
  type: 'start' | 'end',
  value: string | null,
  options: {
    request: any // 请求对象
    parentStartTime?: string // 父级开始时间
    parentEndTime?: string // 父级结束时间
    itemType: 'milestone' | 'iteration' | 'task' // 项目类型
    parentType?: 'project' | 'milestone' // 父级类型
  }
) => {
  const formattedValue = formatDateTime(value)
  const { request, parentStartTime, parentEndTime, itemType, parentType } = options

  if (!value) {
    Message.warning(`请选择${type === 'start' ? '开始' : '结束'}时间`)
    return false
  }

  // 检查开始时间
  if (type === 'start') {
    // 检查是否在父级时间范围内
    if (parentStartTime && dayjs(value).isBefore(dayjs(parentStartTime))) {
      Message.warning(`${itemType}开始时间不能早于${parentType}开始时间`)
      return false
    }
    if (parentEndTime && dayjs(value).isAfter(dayjs(parentEndTime))) {
      Message.warning(`${itemType}开始时间不能晚于${parentType}结束时间`)
      return false
    }
    request.startTime = formattedValue
  }
  // 检查结束时间
  else {
    // 检查是否早于开始时间
    if (dayjs(value).isBefore(dayjs(request.startTime))) {
      Message.warning('结束时间不能早于开始时间')
      return false
    }
    // 检查是否在父级时间范围内
    if (parentEndTime && dayjs(value).isAfter(dayjs(parentEndTime))) {
      Message.warning(`${itemType}结束时间不能晚于${parentType}结束时间`)
      return false
    }
    request.endTime = formattedValue
  }
  return true
}

// 修改里程碑时间变更处理函数
const handleMilestoneTimeChange = (type: 'start' | 'end', value: string | null) => {
  return handleTimeChange(type, value, {
    request: addMileStoneRequest.value,
    parentStartTime: props.projectVo?.startTime,
    parentEndTime: props.projectVo?.endTime,
    itemType: 'milestone',
    parentType: 'project'
  })
}

// 修改迭代时间变更处理函数
const handleIterationTimeChange = (type: 'start' | 'end', value: string | null) => {
  const milestone = currentMilestone.value
  return handleTimeChange(type, value, {
    request: addIterationRequest.value,
    parentStartTime: milestone?.startTime,
    parentEndTime: milestone?.endTime,
    itemType: 'iteration',
    parentType: 'milestone'
  })
}

// 修改任务时间变更处理函数
const handleTaskTimeChange = (type: 'start' | 'end', value: string | null) => {
  return handleTimeChange(type, value, {
    request: addTaskRequest.value,
    itemType: 'task'
  })
}

// 修改编辑器创建处理函数
const handleDescriptionEditorCreated = (
  type: 'milestone' | 'iteration' | 'requirement' | 'task',
  editor: IDomEditor
) => {
  switch (type) {
    case 'milestone':
      if (milestoneDescriptionEditor.value) {
        milestoneDescriptionEditor.value.destroy()
      }
      milestoneDescriptionEditor.value = editor
      break
    case 'iteration':
      if (iterationDescriptionEditor.value) {
        iterationDescriptionEditor.value.destroy()
      }
      iterationDescriptionEditor.value = editor
      break
    case 'requirement':
      if (requirementDescriptionEditor.value) {
        requirementDescriptionEditor.value.destroy()
      }
      requirementDescriptionEditor.value = editor
      break
    case 'task':
      if (taskDescriptionEditor.value) {
        taskDescriptionEditor.value.destroy()
      }
      taskDescriptionEditor.value = editor
      break
  }
}

const handleRemarkEditorCreated = (
  type: 'milestone' | 'iteration' | 'requirement' | 'task',
  editor: IDomEditor
) => {
  switch (type) {
    case 'milestone':
      if (milestoneRemarkEditor.value) {
        milestoneRemarkEditor.value.destroy()
      }
      milestoneRemarkEditor.value = editor
      break
    case 'iteration':
      if (iterationRemarkEditor.value) {
        iterationRemarkEditor.value.destroy()
      }
      iterationRemarkEditor.value = editor
      break
    case 'requirement':
      if (requirementRemarkEditor.value) {
        requirementRemarkEditor.value.destroy()
      }
      requirementRemarkEditor.value = editor
      break
    case 'task':
      if (taskRemarkEditor.value) {
        taskRemarkEditor.value.destroy()
      }
      taskRemarkEditor.value = editor
      break
  }
}
// 点击事件处理
const handleMilestoneClick = (milestone: API.MileStoneVo) => {
  selectedMilestone.value = milestone
  milestoneDetailVisible.value = true
}

const handleIterationClick = (iteration: API.IterationVo) => {
  selectedIteration.value = iteration
  iterationDetailVisible.value = true
}

const handleRequirementClick = (requirement: API.RequirementVo) => {
  selectedRequirement.value = requirement
  requirementDetailVisible.value = true
}

const handleTaskClick = (task: API.TaskVo) => {
  if (!taskDetailVisible.value) {
    selectedTask.value = task
    taskDetailVisible.value = true
  } else {
    taskDetailVisible.value = false
    selectedTask.value = null
  }
}

// 创建迭代窗口
const handleAddIterationInMilestone = (milestone: API.MileStoneVo) => {
  currentMilestone.value = milestone
  // 初始化时间
  initStartDate.value = milestone.startTime || ''
  initEndDate.value = milestone.endTime || ''
  // 重置表单数据
  addIterationRequest.value = {
    title: '',
    startTime: initStartDate.value,
    endTime: initEndDate.value,
    description: '',
    remark: '',
    mileId: currentMilestone.value?.id,
    proId: props.projectVo?.id as number | undefined
  }
  iterationModalVisible.value = true
}

// 创建里程碑表单
const addMileStoneRequest: Ref<API.AddMileStoneRequest> = ref({
  title: '',
  startTime: '',
  endTime: '',
  description: '',
  remark: '',
  proId: props.projectVo?.id as number | undefined
})
const handleAddMilestone = () => {
  // 初始化时间
  initStartDate.value = props.projectVo?.startTime || ''
  initEndDate.value = props.projectVo?.endTime || ''
  // 重置表单数据
  addMileStoneRequest.value = {
    title: '',
    startTime: initStartDate.value,
    endTime: initEndDate.value,
    description: '',
    remark: '',
    proId: props.projectVo?.id as number | undefined
  }
  milestoneModalVisible.value = true
}
// 创建里程碑
const handleSubmitMilestone = async () => {
  try {
    //校验时间
    if (
      dayjs(addMileStoneRequest.value.startTime).isAfter(dayjs(addMileStoneRequest.value.endTime))
    ) {
      Message.error('开始时间不能晚于结束时间')
      return false
    }
    // 格式化时间
    addMileStoneRequest.value.startTime = dayjs(addMileStoneRequest.value.startTime).format(
      'YYYY-MM-DDTHH:mm:ss'
    )
    addMileStoneRequest.value.endTime = dayjs(addMileStoneRequest.value.endTime).format(
      'YYYY-MM-DDTHH:mm:ss'
    )

    const errors = await milestoneFormRef.value?.validate()
    if (errors) {
      Message.error('请填写完整信息')
      return false
    }

    const res: any = await addMilestoneUsingPost(addMileStoneRequest.value)
    if (res.code === 0) {
      Message.success('添加里程碑成功')
      emit('reload', true)
    } else {
      Message.error(res.message || '添加里程碑失败')
      return false
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    milestoneModalVisible.value = false
    //重置表单数据
    addMileStoneRequest.value = {
      title: '',
      startTime: '',
      endTime: '',
      description: '',
      remark: '',
      proId: props.projectVo?.id as number | undefined
    }
  }
}

// 处理显示更多
const handleShowMore = (type: string, id?: number) => {
  if (type === 'projectTasks' && projectTasks.value) {
    displayCounts.projectTasks += 5
  } else if (type === 'milestoneTasks' && id) {
    if (!displayCounts.milestoneTasks[id]) {
      displayCounts.milestoneTasks[id] = 5
    }
    displayCounts.milestoneTasks[id] += 5
  } else if (type === 'iterationTasks' && id) {
    if (!displayCounts.iterationTasks[id]) {
      displayCounts.iterationTasks[id] = 5
    }
    displayCounts.iterationTasks[id] += 5
  } else if (type === 'requirementTasks' && id) {
    if (!displayCounts.requirementTasks[id]) {
      displayCounts.requirementTasks[id] = 5
    }
    displayCounts.requirementTasks[id] += 5
  }
}

// 添加数据状态
const milestones = ref<API.MileStoneVo[]>([])
const projectTasks = ref<API.TaskVo[]>([])

// 初始化数据
const initData = async () => {
  milestones.value = props.projectVo?.mileStoneVoList || []
  projectTasks.value = props.projectVo?.taskVoList || []
}

// 监听 projectVo 变化，重新获取数据
watch(
  () => props.projectVo?.id,
  (newId) => {
    if (newId) {
      initData()
    }
  },
  { immediate: true }
)

// 修改计算属性中的数据源
const iterationOptions = computed(() => {
  // 如果选择了里程碑，只显示该里程碑下的迭代
  if (addTaskRequest.value.mileId) {
    const milestone = milestones.value.find((m) => m.id === addTaskRequest.value.mileId)
    return (
      milestone?.iterationVoList?.map((iteration) => ({
        label: iteration.title,
        value: iteration.id
      })) || []
    )
  }
  // 否则显示所有迭代
  return (milestones.value || []).flatMap(
    (milestone) =>
      milestone.iterationVoList?.map((iterationVo) => ({
        label: iterationVo.title,
        value: iterationVo.id
      })) || []
  )
})

const requirementOptions = computed(() => {
  // 如果选择了迭代，只显示该迭代下的需求
  if (addTaskRequest.value.iterId) {
    const iteration = (milestones.value || [])
      .flatMap((m) => m.iterationVoList || [])
      .find((i) => i.id === addTaskRequest.value.iterId)
    return (
      iteration?.requirementVoList?.map((requirementVo) => ({
        label: requirementVo.title,
        value: requirementVo.id
      })) || []
    )
  }

  // 否则显示所有需求
  return (milestones.value || []).flatMap(
    (milestone) =>
      milestone.iterationVoList?.flatMap(
        (iterationVo) =>
          iterationVo.requirementVoList?.map((requirementVo) => ({
            label: requirementVo.title,
            value: requirementVo.id
          })) || []
      ) || []
  )
})

// 修改里程碑选项计算属性
const milestoneOptions = computed(() =>
  milestones.value.map((milestone) => ({
    label: milestone.title,
    value: milestone.id
  }))
)

// 添加时间格式化函数
const formatDateTime = (time: string | Date | null) => {
  if (!time) return null
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}
const initStartDate = ref(props.projectVo?.startTime || '')
const initEndDate = ref(props.projectVo?.endTime || '')
// 里程碑日期禁用函数
const disabledMilestoneDate = (date: Date) => {
  // 如果没有项目时间范围，则只禁用今天之前的日期
  if (!props.projectVo?.startTime || !props.projectVo?.endTime) {
    return dayjs(date).isBefore(dayjs(), 'day')
  }

  const projectStart = dayjs(props.projectVo.startTime)
  const projectEnd = dayjs(props.projectVo.endTime)
  const currentDate = dayjs(date)

  // 日期必须在项目开始和结束时间之间
  return currentDate.isBefore(projectStart, 'day') || currentDate.isAfter(projectEnd, 'day')
}

// 迭代日期禁用函数
const disabledIterationDate = (date: Date) => {
  const milestone = currentMilestone.value
  if (!milestone) {
    return dayjs(date).isBefore(dayjs(), 'day')
  }

  const milestoneStart = dayjs(milestone.startTime).startOf('day')
  const milestoneEnd = dayjs(milestone.endTime).endOf('day')
  const currentDate = dayjs(date)

  return currentDate.isBefore(milestoneStart) || currentDate.isAfter(milestoneEnd)
}
// 需求日期禁用函数
const disabledRequirementDate = (date: Date) => {
  const iteration = currentIteration.value
  if (!iteration) {
    return dayjs(date).isBefore(dayjs(), 'day')
  }

  const iterationStart = dayjs(iteration.startTime).startOf('day')
  const iterationEnd = dayjs(iteration.endTime).endOf('day')
  const currentDate = dayjs(date)

  return currentDate.isBefore(iterationStart) || currentDate.isAfter(iterationEnd)
}
// 任务日期禁用函数
const disabledTaskDate = (date: Date) => {
  // 如果在需求下创建任务
  if (currentRequirement.value?.startTime && currentRequirement.value?.endTime) {
    const reqStart = dayjs(currentRequirement.value.startTime).startOf('day')
    const reqEnd = dayjs(currentRequirement.value.endTime).endOf('day')
    const currentDate = dayjs(date)
    return currentDate.isBefore(reqStart) || currentDate.isAfter(reqEnd)
  }

  // 如果在迭代下创建任务
  if (currentIteration.value?.startTime && currentIteration.value?.endTime) {
    const iterStart = dayjs(currentIteration.value.startTime).startOf('day')
    const iterEnd = dayjs(currentIteration.value.endTime).endOf('day')
    const currentDate = dayjs(date)
    return currentDate.isBefore(iterStart) || currentDate.isAfter(iterEnd)
  }

  // 如果在里程碑下创建任务
  if (currentMilestone.value?.startTime && currentMilestone.value?.endTime) {
    const mileStart = dayjs(currentMilestone.value.startTime).startOf('day')
    const mileEnd = dayjs(currentMilestone.value.endTime).endOf('day')
    const currentDate = dayjs(date)
    return currentDate.isBefore(mileStart) || currentDate.isAfter(mileEnd)
  }

  // 如果在项目下创建任务
  if (props.projectVo?.startTime && props.projectVo?.endTime) {
    const projectStart = dayjs(props.projectVo.startTime).startOf('day')
    const projectEnd = dayjs(props.projectVo.endTime).endOf('day')
    const currentDate = dayjs(date)
    return currentDate.isBefore(projectStart) || currentDate.isAfter(projectEnd)
  }

  // 如果都没有，则只禁用今天之前的日期
  return dayjs(date).isBefore(dayjs(), 'day')
}
// 添加迭代请求参数
const addIterationRequest: Ref<API.AddIterationRequest> = ref({
  title: '',
  startTime: '',
  endTime: '',
  description: '',
  remark: '',
  proId: props.projectVo?.id as number | undefined,
  mileId: undefined
})
// 添加迭代提交处理函数
const handleSubmitIteration = async () => {
  try {
    //校验时间
    if (
      dayjs(addIterationRequest.value.startTime).isAfter(dayjs(addIterationRequest.value.endTime))
    ) {
      Message.error('开始时间不能晚于结束时间')
      return false
    }
    //格式化时间
    addIterationRequest.value.startTime = dayjs(addIterationRequest.value.startTime).format(
      'YYYY-MM-DDTHH:mm:ss'
    )
    addIterationRequest.value.endTime = dayjs(addIterationRequest.value.endTime).format(
      'YYYY-MM-DDTHH:mm:ss'
    )
    const errors = await iterationFormRef.value?.validate()
    if (errors) {
      Message.error('请填写完整信息')
      return false
    }
    addIterationRequest.value.mileId = currentMilestone.value?.id
    addIterationRequest.value.proId = props.projectVo?.id
    console.log('addIterationRequest:', addIterationRequest.value)
    const res: any = await addIterationUsingPost(addIterationRequest.value)
    if (res.code === 0) {
      Message.success('创建迭代成功')
      emit('reload', true)
    } else {
      Message.error(res.message || '创建迭代失败')
      return false
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    iterationModalVisible.value = false
    //重置表单数据
    addIterationRequest.value = {
      title: '',
      startTime: '',
      endTime: '',
      description: '',
      remark: '',
      proId: props.projectVo?.id as number | undefined,
      mileId: undefined
    }
  }
}

// 编辑器销毁处理
onBeforeUnmount(() => {
  if (taskDescriptionEditor.value) {
    taskDescriptionEditor.value.destroy()
  }
  if (taskRemarkEditor.value) {
    taskRemarkEditor.value.destroy()
  }
  if (milestoneDescriptionEditor.value) {
    milestoneDescriptionEditor.value.destroy()
  }
  if (milestoneRemarkEditor.value) {
    milestoneRemarkEditor.value.destroy()
  }
  if (iterationDescriptionEditor.value) {
    iterationDescriptionEditor.value.destroy()
  }
  if (iterationRemarkEditor.value) {
    iterationRemarkEditor.value.destroy()
  }
  if (requirementDescriptionEditor.value) {
    requirementDescriptionEditor.value.destroy()
  }
  if (requirementRemarkEditor.value) {
    requirementRemarkEditor.value.destroy()
  }
})

// 添加详情弹窗的控制变量
const milestoneDetailVisible = ref(false)
const iterationDetailVisible = ref(false)
const requirementDetailVisible = ref(false)
const taskDetailVisible = ref(false)
// 创建需求窗口
const handleAddRequirementInIteration = (iteration: API.IterationVo) => {
  currentIteration.value = iteration
  // 初始化时间
  initStartDate.value = iteration.startTime || ''
  initEndDate.value = iteration.endTime || ''
  // 重置表单数据
  addRequirementRequest.value = {
    title: '',
    description: '',
    remark: '',
    priority: 0,
    iterId: currentIteration.value?.id,
    mileId: currentIteration.value?.mileId,
    proId: props.projectVo?.id as number | undefined,
    startTime: initStartDate.value,
    endTime: initEndDate.value
  }
  requirementModalVisible.value = true
}
// 处理提交需求
const requirementFormRef = ref<FormInstance | null>(null)
const handleSubmitRequirement = async () => {
  // 校验时间
  if (
    dayjs(addRequirementRequest.value.startTime).isAfter(dayjs(addRequirementRequest.value.endTime))
  ) {
    Message.error('开始时间不能晚于结束时间')
    return false
  }
  // 格式化时间
  addRequirementRequest.value.startTime = dayjs(addRequirementRequest.value.startTime).format(
    'YYYY-MM-DDTHH:mm:ss'
  )
  addRequirementRequest.value.endTime = dayjs(addRequirementRequest.value.endTime).format(
    'YYYY-MM-DDTHH:mm:ss'
  )
  const errors = await requirementFormRef.value?.validate()
  if (errors) {
    Message.error('请填写完整信息')
    return false
  }
  try {
    console.log('addRequirementRequest:', addRequirementRequest.value)
    const res: any = await addRequirementUsingPost(addRequirementRequest.value)
    if (res.code === 0) {
      Message.success('添加需求成功')
      requirementModalVisible.value = false
      emit('reload', true)
    } else {
      Message.error(res.message || '添加需求失败')
      return false
    }
  } catch (error) {
    console.error('添加需求失败:', error)
  } finally {
    // 重置表单数据
    addRequirementRequest.value = {
      title: '',
      startTime: '',
      endTime: '',
      description: '',
      remark: '',
      proId: props.projectVo?.id as number | undefined,
      mileId: undefined
    }
    requirementModalVisible.value = false
  }
}
// 修改 handleAddTask 函数,支持创建项目级任务
const handleAddTask = (params?: {
  milestoneVo?: API.MileStoneVo
  iterationVo?: API.IterationVo
  requirementVo?: API.RequirementVo
}) => {
  //当前里程碑
  currentMilestone.value = params?.milestoneVo || null
  //当前迭代
  currentIteration.value = params?.iterationVo || null
  //当前需求
  currentRequirement.value = params?.requirementVo || null
  //初始化时间
  if (currentRequirement.value) {
    initStartDate.value = currentRequirement.value.startTime || ''
    initEndDate.value = currentRequirement.value.endTime || ''
  } else if (currentIteration.value) {
    initStartDate.value = currentIteration.value.startTime || ''
    initEndDate.value = currentIteration.value.endTime || ''
  } else if (currentMilestone.value) {
    initStartDate.value = currentMilestone.value.startTime || ''
    initEndDate.value = currentMilestone.value.endTime || ''
  } else {
    initStartDate.value = props.projectVo?.startTime || ''
    initEndDate.value = props.projectVo?.endTime || ''
  }
  // 重置表单数据
  addTaskRequest.value = {
    proId: props.projectVo?.id,
    mileId: params?.milestoneVo?.id,
    iterId: params?.iterationVo?.id,
    reqId: params?.requirementVo?.id,
    ownerId: undefined,
    startTime: initStartDate.value,
    endTime: initEndDate.value,
    title: '',
    description: '',
    remark: '',
    priority: PRIORITY_CONFIG.P0.value
  }
  // 确保之前的编辑器实例被销毁
  if (taskDescriptionEditor.value) {
    taskDescriptionEditor.value.destroy()
    taskDescriptionEditor.value = null
  }
  if (taskRemarkEditor.value) {
    taskRemarkEditor.value.destroy()
    taskRemarkEditor.value = null
  }

  // 显示弹窗
  taskModalVisible.value = true
}
// 提交任务的函数
const taskFormRef = ref<FormInstance | null>(null)
const handleSubmitTask = async () => {
  try {
    //校验时间选择
    if (dayjs(addTaskRequest.value.startTime).isAfter(dayjs(addTaskRequest.value.endTime))) {
      Message.error('开始时间不能晚于结束时间')
      return false
    }
    //格式化时间
    addTaskRequest.value.startTime = dayjs(addTaskRequest.value.startTime).format(
      'YYYY-MM-DDTHH:mm:ss'
    )
    addTaskRequest.value.endTime = dayjs(addTaskRequest.value.endTime).format('YYYY-MM-DDTHH:mm:ss')
    if (!taskFormRef.value) return false
    const errors = await taskFormRef.value.validate()
    if (errors) {
      Message.error('请填写完整信息')
      return false // 验证失败返回 false，阻止弹窗关闭
    }

    // 表单验证通过，继续处理提交逻辑
    console.log('提交任务:', addTaskRequest.value)
    // 模拟API调用
    const res: any = await addTaskUsingPost(addTaskRequest.value)
    if (res.code === 0) {
      Message.success('创建任务成功')
      emit('reload', true)
    } else {
      Message.error(res.message || '创建任务失败')
      return false
    }
    return true // 验证通过返回 true，允许弹窗关闭
  } catch (error) {
    console.error('创建任务失败:', error)
    Message.error('创建任务失败，请重试')
    return false // 发生错误返回 false
  } finally {
    taskModalVisible.value = false
    // 重置表单数据
    addTaskRequest.value = {
      proId: props.projectVo?.id,
      mileId: undefined,
      iterId: undefined,
      reqId: undefined,
      ownerId: undefined,
      startTime: props.projectVo?.startTime || '',
      endTime: props.projectVo?.endTime || '',
      title: '',
      description: '',
      remark: '',
      priority: PRIORITY_CONFIG.P0.value
    }
  }
}

// 修改选择处理函数
const handleMilestoneSelect = (id: number | undefined) => {
  addTaskRequest.value.mileId = id
  // 如果清除里程碑，同时清除迭代和需求
  if (!id) {
    addTaskRequest.value.iterId = undefined
    addTaskRequest.value.reqId = undefined
  }
}

const handleIterationSelect = (id: number | undefined) => {
  addTaskRequest.value.iterId = id
  // 如果清除迭代，同时清除需求
  if (!id) {
    addTaskRequest.value.reqId = undefined
  }
}

const handleRequirementSelect = (id: number | undefined) => {
  addTaskRequest.value.reqId = id
}

// 在弹窗关闭时也清理编辑器实例
const handleTaskModalClose = () => {
  if (taskDescriptionEditor.value) {
    taskDescriptionEditor.value.destroy()
    taskDescriptionEditor.value = null
  }
  if (taskRemarkEditor.value) {
    taskRemarkEditor.value.destroy()
    taskRemarkEditor.value = null
  }
  taskModalVisible.value = false
}

// 添加时间格式化函数
const formatDateRange = (startTime?: string, endTime?: string) => {
  if (!startTime || !endTime) return '-'
  return `${startTime.substring(0, 10)} - ${endTime.substring(0, 10)}`
}
</script>

<template>
  <div class="milestone-tasks-list">
    <a-card class="milestone-card">
      <div class="card-header">
        <h3>里程碑与任务</h3>
        <a-dropdown
          @select="
            (key) => {
              if (key === 'task') handleAddTask()
              if (key === 'milestone') handleAddMilestone()
            }
          "
          trigger="hover"
          position="tr"
        >
          <a-button type="text" size="mini" class="add-button">
            <template #icon><icon-plus /></template>
          </a-button>
          <template #content>
            <a-doption value="task">创建任务</a-doption>
            <a-doption value="milestone">创建里程碑</a-doption>
          </template>
        </a-dropdown>
      </div>

      <!-- 里程碑列表 -->
      <div class="optimized-view milestone-container" v-if="milestones.length > 0">
        <a-list :bordered="false" size="large">
          <a-list-item v-for="milestoneVo in milestones" :key="milestoneVo.id">
            <div class="milestone-item">
              <!-- 里程碑头部信息 -->
              <div
                class="item-header milestone-header"
                @click.stop.prevent="handleMilestoneClick(milestoneVo)"
                style="cursor: pointer"
              >
                <!-- 里程碑标题区域 -->
                <div class="item-title-area">
                  <span class="type-label milestone-label">里程碑</span>
                  <span class="item-title milestone-title">{{ milestoneVo.title }}</span>

                  <span class="item-code">{{ milestoneVo.code }}</span>
                  <span class="item-date">
                    {{ formatDateRange(milestoneVo.startTime, milestoneVo.endTime) }}
                  </span>
                </div>
                <div class="item-actions">
                  <a-progress
                    :percent="milestoneVo.progress"
                    :stroke-color="getCompleteColor(milestoneVo.status)"
                    :style="{ width: '120px' }"
                  />
                  <a-tag :color="getCompleteColor(milestoneVo?.status)">
                    {{ getCompleteStatus(milestoneVo?.status) }}
                  </a-tag>
                  <!-- 里程碑添加按钮和下拉菜单 -->
                  <a-dropdown
                    @select="
                      (key) => {
                        if (key === 'task') handleAddTask({ milestoneVo })
                        if (key === 'iteration') handleAddIterationInMilestone(milestoneVo)
                      }
                    "
                    trigger="hover"
                    position="tr"
                    @click.stop
                  >
                    <a-button type="text" size="small" class="add-button" @click.stop>
                      <template #icon><icon-plus /></template>
                    </a-button>
                    <template #content>
                      <a-doption value="task">创建任务</a-doption>
                      <a-doption value="iteration">创建迭代</a-doption>
                    </template>
                  </a-dropdown>
                </div>
              </div>

              <!-- 里程碑下的直接任务 -->
              <div
                v-if="milestoneVo.taskVoList && milestoneVo.taskVoList.length > 0"
                class="milestone-tasks"
              >
                <a-list class="task-list" :bordered="false" size="small">
                  <a-list-item
                    v-for="task in milestoneVo?.taskVoList.slice(
                      0,
                      displayCounts.milestoneTasks[milestoneVo.id] || 5
                    )"
                    :key="task.id"
                    class="task-item"
                    @click="handleTaskClick(task)"
                    style="cursor: pointer"
                  >
                    <div class="item-content task-row">
                      <div class="task-title-container">
                        <span class="type-label task-label">任务</span>
                        <span class="item-title task-title">{{ task.title }}</span>
                        <span class="item-code">{{ task.code }}</span>
                        <span class="item-date">{{
                          formatDateRange(task.startTime, task.endTime)
                        }}</span>
                      </div>
                      <div class="task-info">
                        <a-tag :color="getTaskPriorityColor(task.priority)">
                          {{ getPriorityLabel(task.priority) }}
                        </a-tag>
                        <a-tag :color="getCompleteColor(task.status)">
                          {{ getCompleteStatus(task.status) }}
                        </a-tag>
                      </div>
                    </div>
                  </a-list-item>

                  <!-- 显示更多里程碑任务 -->
                  <a-list-item
                    v-if="
                      milestoneVo.taskVoList.length >
                      (displayCounts.milestoneTasks[milestoneVo?.id] || 5)
                    "
                    class="show-more-item"
                  >
                    <!-- 将点击事件绑定到内部的 div 上 -->
                    <div
                      class="show-more-content"
                      @click.stop.prevent="handleShowMore('milestoneTasks', milestoneVo?.id)"
                    >
                      <span class="show-more-text">加载更多</span>
                    </div>
                  </a-list-item>
                </a-list>
              </div>

              <!-- 里程碑下的迭代列表 -->
              <div
                class="nested-content iterations-container"
                v-if="milestoneVo?.iterationVoList?.length > 0"
              >
                <a-list :bordered="false" size="medium">
                  <a-list-item
                    v-for="iterationVo in milestoneVo?.iterationVoList"
                    :key="iterationVo?.id"
                  >
                    <div class="iteration-item">
                      <!-- 迭代头部信息 -->
                      <div
                        class="item-header iteration-header"
                        @click="handleIterationClick(iterationVo)"
                        style="cursor: pointer"
                      >
                        <!-- 迭代标题区域 -->
                        <div class="item-title-area">
                          <span class="type-label iteration-label">迭代</span>
                          <span class="item-title iteration-title">{{ iterationVo?.title }}</span>

                          <span class="item-code">{{ iterationVo?.code }}</span>
                          <span class="item-date">
                            {{ formatDateRange(iterationVo?.startTime, iterationVo?.endTime) }}
                          </span>
                        </div>
                        <div class="item-actions">
                          <!-- 添加进度条 -->
                          <a-progress
                            :percent="iterationVo?.progress"
                            :stroke-color="getCompleteColor(iterationVo?.status)"
                            :style="{ width: '120px', margin: '0 12px' }"
                          />
                          <a-tag :color="getCompleteColor(iterationVo?.status)">
                            {{ getCompleteStatus(iterationVo?.status) }}
                          </a-tag>
                          <!-- 迭代添加按钮和下拉菜单 -->
                          <a-dropdown
                            @select="
                              (key) => {
                                if (key === 'task') handleAddTask({ milestoneVo, iterationVo })
                                if (key === 'requirement')
                                  handleAddRequirementInIteration(iterationVo)
                              }
                            "
                            trigger="hover"
                            position="tr"
                            @click.stop
                          >
                            <a-button type="text" size="small" class="add-button" @click.stop>
                              <template #icon><icon-plus /></template>
                            </a-button>
                            <template #content>
                              <a-doption value="requirement">创建需求</a-doption>
                              <a-doption value="task">创建任务</a-doption>
                            </template>
                          </a-dropdown>
                        </div>
                      </div>

                      <!-- 迭代下的直接任务 -->
                      <div
                        v-if="iterationVo?.taskVoList && iterationVo?.taskVoList.length > 0"
                        class="iteration-tasks"
                      >
                        <a-list class="task-list" :bordered="false" size="small">
                          <a-list-item
                            v-for="task in iterationVo?.taskVoList.slice(
                              0,
                              displayCounts.iterationTasks[iterationVo?.id] || 5
                            )"
                            :key="task.id"
                            class="task-item"
                            @click="handleTaskClick(task)"
                            style="cursor: pointer"
                          >
                            <div class="item-content task-row">
                              <div class="task-title-container">
                                <span class="type-label task-label">任务</span>
                                <span class="item-title task-title">{{ task.title }}</span>
                                <span class="item-code">{{ task.code }}</span>
                                <span class="item-date">{{
                                  formatDateRange(task.startTime, task.endTime)
                                }}</span>
                              </div>
                              <div class="task-info">
                                <a-tag :color="getTaskPriorityColor(task.priority)">
                                  {{ task.priority }}
                                </a-tag>
                                <a-tag :color="getCompleteColor(task.status)">
                                  {{ getCompleteStatus(task.status) }}
                                </a-tag>
                              </div>
                            </div>
                          </a-list-item>

                          <!-- 显示更多迭代任务 -->
                          <a-list-item
                            v-if="
                              iterationVo?.taskVoList.length >
                              (displayCounts.iterationTasks[iterationVo?.id] || 5)
                            "
                            class="show-more-item"
                            @click="handleShowMore('iterationTasks', iterationVo?.id)"
                          >
                            <div class="show-more-content">
                              <span class="show-more-text">加载更多</span>
                            </div>
                          </a-list-item>
                        </a-list>
                      </div>

                      <!-- 迭代下的需求列表 -->
                      <div
                        class="nested-content requirements-container"
                        v-if="iterationVo?.requirementVoList?.length > 0"
                      >
                        <a-list :bordered="false" size="small">
                          <a-list-item
                            v-for="requirementVo in iterationVo?.requirementVoList"
                            :key="requirementVo?.id"
                            style="cursor: pointer"
                          >
                            <div class="requirement-item">
                              <!-- 需求头部信息 -->
                              <div
                                class="item-header requirement-header"
                                @click.stop="handleRequirementClick(requirementVo)"
                                style="cursor: pointer"
                              >
                                <!-- 需求标题区域 -->
                                <div class="item-title-area">
                                  <span class="type-label requirement-label">需求</span>
                                  <span
                                    class="item-title requirement-title clickable"
                                    @click="handleRequirementClick(requirementVo)"
                                  >
                                    {{ requirementVo?.title }}
                                  </span>
                                  <span class="item-code">{{ requirementVo?.code }}</span>
                                  <span class="item-date">
                                    {{
                                      formatDateRange(
                                        requirementVo?.startTime,
                                        requirementVo?.endTime
                                      )
                                    }}
                                  </span>
                                </div>
                                <div class="item-actions">
                                  <!-- 添加进度条 -->
                                  <a-progress
                                    :percent="requirementVo?.progress"
                                    :stroke-color="getCompleteColor(requirementVo?.status)"
                                    :style="{ width: '120px', margin: '0 12px' }"
                                  />
                                  <!-- 添加状态标签 -->
                                  <a-tag :color="getCompleteColor(requirementVo?.status)">
                                    {{ getCompleteStatus(requirementVo?.status) }}
                                  </a-tag>
                                  <!-- 添加优先级标签 -->
                                  <a-tag :color="getTaskPriorityColor(requirementVo?.priority)">
                                    {{ getPriorityLabel(requirementVo?.priority) }}
                                  </a-tag>
                                  <!-- 操作按钮 -->
                                  <a-button-group>
                                    <a-button
                                      type="text"
                                      size="small"
                                      class="add-button"
                                      @click.stop="
                                        handleAddTask({ milestoneVo, iterationVo, requirementVo })
                                      "
                                    >
                                      <template #icon>
                                        <icon-plus />
                                      </template>
                                    </a-button>
                                  </a-button-group>
                                </div>
                              </div>

                              <!-- 需求下的任务列表 -->
                              <div
                                class="nested-content"
                                v-if="requirementVo?.taskVoList?.length > 0"
                              >
                                <a-list class="task-list" :bordered="false" size="small">
                                  <a-list-item
                                    v-for="taskVo in (requirementVo?.taskVoList ?? []).slice(
                                      0,
                                      displayCounts.requirementTasks[requirementVo?.id] || 5
                                    )"
                                    :key="taskVo?.id"
                                    class="task-item"
                                    @click.stop="handleTaskClick(taskVo)"
                                    style="cursor: pointer"
                                  >
                                    <div class="item-content task-row">
                                      <div class="task-title-container">
                                        <span class="type-label task-label">任务</span>
                                        <span
                                          class="item-title task-title clickable"
                                          @click="handleTaskClick(taskVo)"
                                        >
                                          {{ taskVo?.title }}
                                        </span>
                                        <span class="item-code">{{ taskVo?.code }}</span>
                                        <span class="item-date">
                                          {{ formatDateRange(taskVo?.startTime, taskVo?.endTime) }}
                                        </span>
                                      </div>
                                      <div class="task-info">
                                        <a-tag :color="getTaskPriorityColor(taskVo?.priority)">
                                          {{ taskVo?.priority }}
                                        </a-tag>
                                        <a-tag :color="getCompleteColor(taskVo?.status)">
                                          {{ getCompleteStatus(taskVo?.status) }}
                                        </a-tag>
                                      </div>
                                    </div>
                                  </a-list-item>

                                  <!-- 显示更多需求任务 -->
                                  <a-list-item
                                    v-if="
                                      (requirementVo?.taskVoList?.length ?? 0) >
                                      (displayCounts.requirementTasks[requirementVo?.id] || 5)
                                    "
                                    class="show-more-item"
                                    @click.stop="
                                      handleShowMore('requirementTasks', requirementVo?.id)
                                    "
                                  >
                                    <div class="show-more-content">
                                      <span class="show-more-text">加载更多</span>
                                    </div>
                                  </a-list-item>
                                </a-list>
                              </div>
                            </div>
                          </a-list-item>
                        </a-list>
                      </div>
                    </div>
                  </a-list-item>
                </a-list>
              </div>
            </div>
          </a-list-item>
        </a-list>
      </div>

      <!-- 项目直属任务列表 -->
      <div v-if="projectTasks?.length > 0" class="project-tasks">
        <a-list class="task-list milestone-task-list" :bordered="false" size="small">
          <a-list-item
            v-for="task in projectTasks.slice(0, displayCounts.projectTasks)"
            :key="task.id"
            class="task-item"
            @click="handleTaskClick(task)"
            style="cursor: pointer"
          >
            <div class="item-content task-row">
              <div class="task-title-container">
                <span class="type-label task-label">任务</span>
                <span class="item-title task-title">{{ task.title }}</span>
                <span class="item-code">{{ task.code }}</span>
                <span class="item-date">{{ formatDateRange(task.startTime, task.endTime) }}</span>
              </div>
              <div class="task-info">
                <a-tag :color="getTaskPriorityColor(task.priority)">
                  {{ getPriorityLabel(task.priority) }}
                </a-tag>
                <a-tag :color="getCompleteColor(task.status)">
                  {{ getCompleteStatus(task.status) }}
                </a-tag>
              </div>
            </div>
          </a-list-item>

          <!-- 显示更多项目任务 -->
          <a-list-item
            v-if="projectTasks.length > displayCounts.projectTasks"
            class="show-more-item"
            @click="handleShowMore('projectTasks')"
          >
            <div class="show-more-content">
              <span class="show-more-text">加载更多</span>
            </div>
          </a-list-item>
        </a-list>
      </div>
    </a-card>

    <!-- 1. 里程碑创建/编辑弹窗 -->
    <a-modal
      v-model:visible="milestoneModalVisible"
      title="添加里程碑"
      @cancel="milestoneModalVisible = false"
      @before-ok="handleSubmitMilestone"
      modal-class="milestone-modal"
      width="auto"
      v-if="milestoneModalVisible"
      :draggable="true"
    >
      <a-form
        ref="milestoneFormRef"
        :model="addMileStoneRequest"
        :rules="milestoneRules"
        layout="vertical"
        class="milestone-form"
      >
        <!-- 标题 -->
        <a-form-item field="title" label="里程碑标题" validate-trigger="blur">
          <a-input v-model="addMileStoneRequest.title" placeholder="请输入里程碑标题" allow-clear />
        </a-form-item>

        <!-- 时间选择 -->
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="startTime" label="开始时间">
              <a-date-picker
                v-model="addMileStoneRequest.startTime"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择开始时间"
                style="width: 100%"
                :disabled-date="disabledMilestoneDate"
                :default-value="initStartDate"
                @change="(value) => handleMilestoneTimeChange('start', value)"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="endTime" label="结束时间">
              <a-date-picker
                v-model="addMileStoneRequest.endTime"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择结束时间"
                style="width: 100%"
                :disabled-date="disabledMilestoneDate"
                :default-value="initEndDate"
                @change="(value) => handleMilestoneTimeChange('end', value)"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <!-- 描述编辑器 -->
        <a-form-item field="description" label="描述">
          <div class="editor-container">
            <Toolbar
              style="border-bottom: 1px solid var(--color-border)"
              :editor="milestoneDescriptionEditor"
              mode="default"
            />
            <Editor
              v-model="addMileStoneRequest.description"
              :default-config="editorConfig"
              :style="editorStyle"
              mode="default"
              v-if="milestoneModalVisible"
              @on-created="(editor) => handleDescriptionEditorCreated('milestone', editor)"
            />
          </div>
        </a-form-item>

        <!-- 备注编辑器 -->
        <a-form-item field="remark" label="备注">
          <div class="editor-container">
            <Toolbar
              style="border-bottom: 1px solid var(--color-border)"
              :editor="milestoneRemarkEditor"
              mode="default"
            />
            <Editor
              v-model="addMileStoneRequest.remark"
              :default-config="editorConfig"
              :style="editorStyle"
              mode="default"
              v-if="milestoneModalVisible"
              @on-created="(editor) => handleRemarkEditorCreated('milestone', editor)"
            />
          </div>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 2. 创建迭代弹窗 -->
    <a-modal
      v-model:visible="iterationModalVisible"
      title="添加迭代"
      @cancel="iterationModalVisible = false"
      @before-ok="handleSubmitIteration"
      modal-class="iteration-modal"
      width="auto"
      v-if="iterationModalVisible"
      :draggable="true"
    >
      <a-form
        ref="iterationFormRef"
        :model="addIterationRequest"
        :rules="iterationRules"
        layout="vertical"
        class="iteration-form"
      >
        <!-- 标题 -->
        <a-form-item field="title" label="迭代标题" validate-trigger="blur">
          <a-input v-model="addIterationRequest.title" placeholder="请输入迭代标题" allow-clear />
        </a-form-item>

        <!-- 时间选择 -->
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="startTime" label="开始时间">
              <a-date-picker
                v-model="addIterationRequest.startTime"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择开始时间"
                style="width: 100%"
                :disabled-date="disabledIterationDate"
                :default-value="initStartDate"
                @change="(value) => handleIterationTimeChange('start', value)"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="endTime" label="结束时间">
              <a-date-picker
                v-model="addIterationRequest.endTime"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择结束时间"
                style="width: 100%"
                :disabled-date="disabledIterationDate"
                :default-value="initEndDate"
                @change="(value) => handleIterationTimeChange('end', value)"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <!-- 关联里程碑和迭代 -->
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="milestoneId" label="关联里程碑">
              <a-select
                v-model="addIterationRequest.mileId"
                placeholder="请选择里程碑"
                allow-clear
                @change="handleMilestoneSelect"
              >
                <a-option
                  v-for="option in milestoneOptions"
                  :key="option.value"
                  :value="option.value"
                  :label="option.label"
                />
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <!-- 描述编辑器 -->
        <a-form-item field="description" label="描述">
          <div class="editor-container">
            <Toolbar
              style="border-bottom: 1px solid var(--color-border)"
              :editor="iterationDescriptionEditor"
              mode="default"
            />
            <Editor
              v-model="addIterationRequest.description"
              :default-config="editorConfig"
              :style="editorStyle"
              mode="default"
              v-if="iterationModalVisible"
              @on-created="(editor) => handleDescriptionEditorCreated('iteration', editor)"
            />
          </div>
        </a-form-item>

        <!-- 备注编辑器 -->
        <a-form-item field="remark" label="备注">
          <div class="editor-container">
            <Toolbar
              style="border-bottom: 1px solid var(--color-border)"
              :editor="iterationRemarkEditor"
              mode="default"
            />
            <Editor
              v-model="addIterationRequest.remark"
              :default-config="editorConfig"
              :style="editorStyle"
              mode="default"
              v-if="iterationModalVisible"
              @on-created="(editor) => handleRemarkEditorCreated('iteration', editor)"
            />
          </div>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 3. 需求创建/编辑弹窗 -->
    <a-modal
      v-model:visible="requirementModalVisible"
      title="添加需求"
      @cancel="requirementModalVisible = false"
      @before-ok="handleSubmitRequirement"
      modal-class="requirement-modal"
      width="auto"
      v-if="requirementModalVisible"
      :draggable="true"
    >
      <a-form
        ref="requirementFormRef"
        :model="addRequirementRequest"
        :rules="requirementRules"
        layout="vertical"
        class="requirement-form"
      >
        <!-- 标题 -->
        <a-form-item field="title" label="需求标题" validate-trigger="blur">
          <a-input v-model="addRequirementRequest.title" placeholder="请输入需求标题" allow-clear />
        </a-form-item>

        <!-- 优先级和负责人放在同一行 -->
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="priority" label="优先级" validate-trigger="change">
              <a-select v-model="addRequirementRequest.priority" placeholder="请选择优先级">
                <a-option :value="PRIORITY_CONFIG.P0.value">
                  <span :style="{ color: PRIORITY_CONFIG.P0.color, fontWeight: 'bold' }">{{
                    PRIORITY_CONFIG.P0.label
                  }}</span>
                  - {{ PRIORITY_CONFIG.P0.description }}
                </a-option>
                <a-option :value="PRIORITY_CONFIG.P1.value">
                  <span :style="{ color: PRIORITY_CONFIG.P1.color, fontWeight: 'bold' }">{{
                    PRIORITY_CONFIG.P1.label
                  }}</span>
                  - {{ PRIORITY_CONFIG.P1.description }}
                </a-option>
                <a-option :value="PRIORITY_CONFIG.P2.value">
                  <span :style="{ color: PRIORITY_CONFIG.P2.color, fontWeight: 'bold' }">{{
                    PRIORITY_CONFIG.P2.label
                  }}</span>
                  - {{ PRIORITY_CONFIG.P2.description }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="ownerId" label="负责人">
              <a-select v-model="addRequirementRequest.ownerId" placeholder="请选择负责人">
                <a-option
                  v-for="member in props?.projectVo?.members"
                  :key="member.id"
                  :value="member.id"
                >
                {{ member.name + `(` + member.username + `)` }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <!-- 时间选择 -->
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="startTime" label="开始时间">
              <a-date-picker
                v-model="addRequirementRequest.startTime"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择开始时间"
                style="width: 100%"
                :disabled-date="disabledRequirementDate"
                :default-value="initStartDate"
                @change="(value) => handleTaskTimeChange('start', value)"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="endTime" label="结束时间">
              <a-date-picker
                v-model="addRequirementRequest.endTime"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择结束时间"
                style="width: 100%"
                :disabled-date="disabledRequirementDate"
                :default-value="initEndDate"
                @change="(value) => handleTaskTimeChange('end', value)"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <!-- 关联里程碑和迭代 -->
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="milestoneId" label="关联里程碑">
              <a-select
                v-model="addRequirementRequest.mileId"
                placeholder="请选择里程碑"
                allow-clear
                @change="handleMilestoneSelect"
              >
                <a-option
                  v-for="option in milestoneOptions"
                  :key="option.value"
                  :value="option.value"
                  :label="option.label"
                />
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="iterationId" label="关联迭代">
              <a-select
                v-model="addRequirementRequest.iterId"
                placeholder="请选择迭代"
                allow-clear
                :disabled="!addRequirementRequest.mileId"
              >
                <a-option
                  v-for="option in iterationOptions"
                  :key="option.value"
                  :value="option.value"
                  :label="option.label"
                />
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <!-- 描述编辑器 -->
        <a-form-item field="description" label="描述">
          <div class="editor-container">
            <Toolbar
              style="border-bottom: 1px solid var(--color-border)"
              :editor="requirementDescriptionEditor"
              mode="default"
            />
            <Editor
              v-model="addRequirementRequest.description"
              :default-config="editorConfig"
              :style="editorStyle"
              mode="default"
              v-if="requirementModalVisible"
              @on-created="(editor) => handleDescriptionEditorCreated('requirement', editor)"
            />
          </div>
        </a-form-item>

        <!-- 备注编辑器 -->
        <a-form-item field="remark" label="备注">
          <div class="editor-container">
            <Toolbar
              style="border-bottom: 1px solid var(--color-border)"
              :editor="requirementRemarkEditor"
              mode="default"
            />
            <Editor
              v-model="addRequirementRequest.remark"
              :default-config="editorConfig"
              :style="editorStyle"
              mode="default"
              v-if="requirementModalVisible"
              @on-created="(editor) => handleRemarkEditorCreated('requirement', editor)"
            />
          </div>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 4. 任务创建/编辑弹窗 -->
    <a-modal
      v-model:visible="taskModalVisible"
      title="添加任务"
      @cancel="handleTaskModalClose"
      @before-ok="handleSubmitTask"
      modal-class="task-modal"
      width="auto"
      :draggable="true"
    >
      <a-form
        ref="taskFormRef"
        :model="addTaskRequest"
        :rules="taskRules"
        layout="vertical"
        class="task-form"
      >
        <!-- 标题 -->
        <a-form-item field="title" label="任务标题" validate-trigger="blur">
          <a-input v-model="addTaskRequest.title" placeholder="请输入任务标题" allow-clear />
        </a-form-item>

        <!-- 优先级和负责人放在同一行 -->
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="priority" label="优先级" validate-trigger="change">
              <a-select v-model="addTaskRequest.priority" placeholder="请选择优先级">
                <a-option :value="PRIORITY_CONFIG.P0.value">
                  <span :style="{ color: PRIORITY_CONFIG.P0.color }">{{
                    PRIORITY_CONFIG.P0.label
                  }}</span>
                  - {{ PRIORITY_CONFIG.P0.description }}
                </a-option>
                <a-option :value="PRIORITY_CONFIG.P1.value">
                  <span :style="{ color: PRIORITY_CONFIG.P1.color }">{{
                    PRIORITY_CONFIG.P1.label
                  }}</span>
                  - {{ PRIORITY_CONFIG.P1.description }}
                </a-option>
                <a-option :value="PRIORITY_CONFIG.P2.value">
                  <span :style="{ color: PRIORITY_CONFIG.P2.color }">{{
                    PRIORITY_CONFIG.P2.label
                  }}</span>
                  - {{ PRIORITY_CONFIG.P2.description }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="ownerId" label="负责人">
              <a-select v-model="addTaskRequest.ownerId" placeholder="请选择负责人">
                <a-option
                  v-for="member in props?.projectVo?.members"
                  :key="member.id"
                  :value="member.id"
                >
                {{ member.name + `(` + member.username + `)` }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <!-- 时间选择 -->
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="startTime" label="开始时间">
              <a-date-picker
                v-model="addTaskRequest.startTime"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择开始时间"
                style="width: 100%"
                :disabled-date="disabledTaskDate"
                :default-value="initStartDate"
                @change="(value) => handleTaskTimeChange('start', value)"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="endTime" label="结束时间">
              <a-date-picker
                v-model="addTaskRequest.endTime"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择结束时间"
                style="width: 100%"
                :disabled-date="disabledTaskDate"
                :default-value="initEndDate"
                @change="(value) => handleTaskTimeChange('end', value)"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <!-- 三个关联选择项放在同一行 -->
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item field="mileId" label="关联里程碑">
              <a-select
                v-model="addTaskRequest.mileId"
                placeholder="请选择里程碑"
                allow-clear
                @change="handleMilestoneSelect"
              >
                <a-option
                  v-for="option in milestoneOptions"
                  :key="option.value"
                  :value="option.value"
                  :label="option.label"
                />
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="iterId" label="关联迭代">
              <a-select
                v-model="addTaskRequest.iterId"
                placeholder="请选择迭代"
                allow-clear
                @change="handleIterationSelect"
                :disabled="!addTaskRequest.mileId"
              >
                <a-option
                  v-for="option in iterationOptions"
                  :key="option.value"
                  :value="option.value"
                  :label="option.label"
                />
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="reqId" label="关联需求">
              <a-select
                v-model="addTaskRequest.reqId"
                placeholder="请选择需求"
                allow-clear
                @change="handleRequirementSelect"
              >
                <a-option
                  v-for="option in requirementOptions"
                  :key="option.value"
                  :value="option.value"
                  :label="option.label"
                />
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <!-- 描述编辑器 -->
        <a-form-item field="description" label="描述">
          <div class="editor-container">
            <Toolbar
              style="border-bottom: 1px solid var(--color-border)"
              :editor="taskDescriptionEditor"
              mode="default"
            />
            <Editor
              v-model="addTaskRequest.description"
              :default-config="editorConfig"
              :style="editorStyle"
              mode="default"
              v-if="taskModalVisible"
              @on-created="(editor) => handleDescriptionEditorCreated('task', editor)"
            />
          </div>
        </a-form-item>

        <!-- 备注编辑器 -->
        <a-form-item field="remark" label="备注">
          <div class="editor-container">
            <Toolbar
              style="border-bottom: 1px solid var(--color-border)"
              :editor="taskRemarkEditor"
              mode="default"
            />
            <Editor
              v-model="addTaskRequest.remark"
              :default-config="editorConfig"
              :style="editorStyle"
              mode="default"
              v-if="taskModalVisible"
              @on-created="(editor) => handleRemarkEditorCreated('task', editor)"
            />
          </div>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 5. 任务视图弹窗 -->
    <TaskView
      v-if="taskDetailVisible"
      :visible="taskDetailVisible"
      :taskId="selectedTask?.id"
      @update:visible="
        async () => {
          await emit('reload', true)
          taskDetailVisible = false
        }
      "
    />
    <!-- 6. 需求视图弹窗 -->
    <RequirementView
      v-if="requirementDetailVisible"
      :visible="requirementDetailVisible"
      :requirementId="selectedRequirement?.id"
      @update:visible="
        async () => {
          await emit('reload', true)
          requirementDetailVisible = false
        }
      "
    />

    <!-- 7.里程碑视图弹窗 -->
    <MileStoneView
      v-if="milestoneDetailVisible"
      :visible="milestoneDetailVisible"
      :milestoneId="selectedMilestone?.id"
      @update:visible="
        async () => {
          await emit('reload', true)
          milestoneDetailVisible = false
        }
      "
    />
    <!-- 8.迭代视图弹窗 -->
    <IterationView
      v-if="iterationDetailVisible"
      :visible="iterationDetailVisible"
      :iterationId="selectedIteration?.id"
      @update:visible="
        async () => {
          await emit('reload', true)
          iterationDetailVisible = false
        }
      "
    />
  </div>
</template>

<style scoped>
/* 基础布局样式 */
.milestone-tasks-list {
  width: 100%;
}

/* 里程碑卡片样式 */
.milestone-card {
  width: 100%;
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

/* 移除卡片内部容器的背景色和边框 */
.optimized-view,
.milestone-container {
  background: transparent;
  border: none;
}

/* 移除列表边框和背景 */
:deep(.arco-list) {
  background: transparent;
  border: none;
}

:deep(.arco-list-wrapper) {
  background: transparent;
  border: none;
}

:deep(.arco-list-content) {
  background: transparent;
  border: none;
}

/* 移除列表项的边框和背景 */
:deep(.arco-list-item) {
  background: transparent;
  border: none;
  padding-left: 0;
  padding-right: 0;
}

/* 里程碑项样式 */
:deep(.arco-list-item .milestone-item) {
  border: none;
  box-shadow: none;
  padding: 0;
  margin-bottom: 16px;
  background: transparent;
}

/* 里程碑头部样式 */
.milestone-header {
  background-color: rgba(64, 128, 255, 0.15);
  border-left: 4px solid rgb(64, 128, 255);
  padding: 12px;
  border-radius: 4px;
}

.milestone-title {
  color: rgb(29, 78, 216);
}

/* 迭代项样式 */
.iteration-header {
  background-color: rgba(0, 180, 42, 0.15);
  border-left: 3px solid rgb(0, 180, 42);
  padding: 12px;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 需求项样式 */
.requirement-header {
  background-color: rgba(201, 55, 157, 0.15);
  border-left: 3px solid rgb(201, 55, 157);
  padding: 12px;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 任务项样式 */
.task-item {
  background-color: rgba(250, 173, 20, 0.05) !important;
  border-radius: 4px;
  margin-bottom: 8px;
  border: 1px solid rgba(250, 173, 20, 0.2) !important;
  border-left: 2px solid rgb(250, 173, 20) !important;
  padding: 8px !important;
}

.task-title {
  color: rgb(194, 120, 3);
}

/* 标题标签样式 */
.type-label {
  display: inline-block;
  padding: 3px 7px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
  margin-right: 8px;
  color: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.milestone-label {
  background-color: rgb(64, 128, 255);
}

.iteration-label {
  background-color: rgb(0, 180, 42);
}

.requirement-label {
  background-color: rgb(201, 55, 157);
}

.task-label {
  background-color: rgb(250, 173, 20);
}

/* 嵌套内容样式 */
.nested-content {
  margin-left: 24px;
}

/* 为不同层级设置不同的嵌套边框颜色 */
.milestone-item .nested-content {
  border-left-color: rgba(64, 128, 255, 0.5);
}

.iteration-item .nested-content {
  border-left-color: rgba(0, 180, 42, 0.5);
}

.requirement-item .nested-content {
  border-left-color: rgba(201, 55, 157, 0.5);
}

/* 添加按钮样式 */
.add-button {
  opacity: 0.6;
  transition: opacity 0.2s;
}

.add-button:hover {
  opacity: 1;
  color: var(--color-primary);
}

/* 操作区样式 */
.item-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 标题区域样式 */
.item-title-area {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

/* 时间样式，鲜艳一点 */
.item-date {
  color: #1b161a7c;
  font-size: 13px;
  white-space: nowrap;
  margin-left: 5px; /* 添加这一行，向右移动5px */
}

/* 任务行样式 */
.task-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.task-title-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.task-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 项目任务列表样式 */
.project-tasks {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px dashed var(--color-border);
}

/* 显示更多按钮样式 */
.show-more-item {
  background-color: transparent !important;
  border: none !important;
  cursor: pointer;
  padding: 8px 0 !important;
  text-align: center;
  margin-top: 4px;
}

.show-more-content {
  width: 100%;
  display: flex;
  justify-content: center;
}

.show-more-text {
  font-size: 14px;
  color: var(--color-text-3);
  background-color: var(--color-fill-2);
  padding: 4px 12px;
  border-radius: 16px;
  transition: all 0.2s;
}

.show-more-item:hover .show-more-text {
  color: var(--color-primary);
  background-color: var(--color-primary-light-4);
}

/* 任务列表样式 */
.milestone-tasks {
  margin-left: 24px;
}
.task-list {
  display: flex;
  flex-direction: column;
  margin-left: 0;
  padding-left: 0;
}
.milestone-task-list {
  margin-left: 16px;
}
/* 悬浮效果 */
.task-item:hover {
  box-shadow: 0 2px 4px rgba(250, 173, 20, 0.2) !important;
  background-color: rgba(250, 173, 20, 0.1) !important;
}

/* 标题样式 */
.section-title {
  font-size: 14px;
  font-weight: 500;
  color: var(--color-text-2);
  margin: 8px 0;
  padding-left: 4px;
  border-left: 3px solid var(--color-primary);
  display: flex;
  align-items: center;
  gap: 6px;
}

/* 下拉菜单项样式 */
:deep(.arco-dropdown-option) {
  padding: 8px 16px;
}

/* 添加详情弹窗相关样式 */
.milestone-detail-content,
.iteration-detail-content,
.requirement-detail-content,
.task-detail-content {
  padding: 16px;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h3 {
  font-size: 16px;
  margin-bottom: 16px;
  color: var(--color-text-1);
}

.info-item {
  display: flex;
  margin-bottom: 12px;
}

.info-item .label {
  width: 80px;
  color: var(--color-text-3);
}

.status {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 13px;
}

.status.completed {
  background-color: rgb(var(--success-1));
  color: rgb(var(--success-6));
}

.status.in_progress {
  background-color: rgb(var(--primary-1));
  color: rgb(var(--primary-6));
}

.status.pending {
  background-color: rgb(var(--gray-1));
  color: rgb(var(--gray-6));
}

.status.overdue {
  background-color: rgb(var(--danger-1));
  color: rgb(var(--danger-6));
}

:deep(.milestone-modal .arco-modal-content),
:deep(.iteration-modal .arco-modal-content) {
  width: 100%;
  padding: 0;
}

:deep(.milestone-modal .arco-modal-body),
:deep(.iteration-modal .arco-modal-body) {
  max-height: 80vh;
  overflow-y: auto;
  padding: 24px 32px;
  width: 100%;
  box-sizing: border-box;
}

.milestone-form,
.iteration-form,
.requirement-form,
.task-form {
  width: 100%;
  min-width: 320px;
  max-width: 1080px;
}

/* 确保所有表单项都占满宽度 */
:deep(.milestone-modal .arco-form-item),
:deep(.iteration-modal .arco-form-item) {
  width: 100%;
}

:deep(.milestone-modal .arco-form-item-content),
:deep(.iteration-modal .arco-form-item-content) {
  width: 100%;
}

.editor-container {
  border: 1px solid var(--color-border);
  border-radius: 4px;
}

/* 可点击标题样式 */
.requirement-title.clickable,
.task-title.clickable {
  cursor: pointer;
  transition: color 0.2s;
}

.requirement-title.clickable:hover {
  color: rgb(201, 55, 157);
}

.task-title.clickable:hover {
  color: rgb(250, 173, 20);
}

/* 进度条样式调整 */
:deep(.arco-progress) {
  margin: 0;
}

/* 标签样式调整 */
:deep(.arco-tag) {
  margin: 0;
}

/* 优先级选择器样式 */
:deep(.arco-select-option) {
  padding: 8px 12px;
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.arco-select-option:hover) {
  background-color: var(--color-fill-2);
}

:deep(.arco-select-option span:first-child) {
  font-weight: bold;
  min-width: 24px;
  text-align: center;
}

/* 修改弹窗样式 */
:deep(.milestone-modal),
:deep(.iteration-modal),
:deep(.requirement-modal),
:deep(.task-modal) {
  width: 90% !important;
  max-width: 1080px !important;
  min-width: 320px !important;
}

/* 确保弹窗内容区域也是响应式的 */
:deep(.arco-modal-content) {
  width: 100%;
  padding: 0;
}

:deep(.arco-modal-body) {
  max-height: 80vh;
  overflow-y: auto;
  padding: 24px;
  width: 100%;
  box-sizing: border-box;
}

/* 添加编号样式 */
.item-code {
  color: var(--color-text-3);
  font-size: 13px;
  font-family: monospace;
  padding: 2px 6px;
  background-color: var(--color-fill-2);
  border-radius: 4px;
  margin-right: 8px;
}

/* 调整现有样式以适应新增的编号 */
.item-title-area {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.task-title-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 其他现有样式保持不变 */

/* 修改头部布局样式 */
.item-header {
  display: flex;
  flex-wrap: wrap; /* 允许换行 */
  gap: 12px; /* 设置间距 */
  padding: 12px;
  border-radius: 4px;
}

/* 标题区域样式 */
.item-title-area {
  display: flex;
  align-items: center;
  flex-wrap: wrap; /* 允许换行 */
  gap: 8px;
  min-width: 200px; /* 设置最小宽度 */
  flex: 1;
}

/* 操作区域样式 */
.item-actions {
  display: flex;
  align-items: center;
  flex-wrap: wrap; /* 允许换行 */
  gap: 8px;
  justify-content: flex-end;
}

/* 任务行样式 */
.task-row {
  display: flex;
  flex-wrap: wrap; /* 允许换行 */
  gap: 8px;
  width: 100%;
}

/* 任务标题容器 */
.task-title-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap; /* 允许换行 */
  gap: 8px;
  min-width: 200px; /* 设置最小宽度 */
  flex: 1;
}

/* 任务信息区域 */
.task-info {
  display: flex;
  align-items: center;
  flex-wrap: wrap; /* 允许换行 */
  gap: 8px;
}

/* 进度条容器样式 */
.progress-container {
  min-width: 120px;
  margin: 0;
}

/* 标签样式 */
:deep(.arco-tag) {
  margin: 4px 0;
}
</style>
